/**
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * 
 */
package org.jiopi.ibean.kernel.util;

import java.io.File;
import java.net.URL;

/**
 * 
 * kernel的文件工具类
 * 
 * @since iBean0.1 2010.4.25
 * @version 0.1
 */
public class FileUtil extends org.jiopi.ibean.share.ShareUtil.FileUtil {
	
	/**
	 * 将目录路径转换为标准URI目录格式,即有'/'结尾的形式
	 * 
	 * @param path
	 * @return
	 */
	public static String correctURIDirPath(String path){
		if(path == null || path.length()==0) return path;
		if(path.endsWith("/")){
			return path;
		}
		return path+"/";
	}
	
	/**
	 * 得到文件名
	 * @param filePath
	 * @param extension 是否需要扩展名
	 * @return
	 */
	public static String getFileName(String filePath,boolean extension){
		if(filePath == null)return null;
		int pos = filePath.lastIndexOf('/')+1;
		int pos2 = filePath.length();
		if(!extension) pos2 = filePath.lastIndexOf('.');
		if(pos<0)pos=0;
		if(pos2<0)pos=filePath.length();
		return filePath.substring(pos,pos2);
	}
	
	/**
	 * get jar file object by given URL of a resource URL in a jar
	 * @param resourceURL
	 * @return null is not a jar file or is not a dir
	 */
	public static File getJarDirFileByResourceURL(URL resourceURL){
		String resourceFilePath = resourceURL.getFile();
		if(resourceFilePath.endsWith(".jar")){
			return new File(resourceFilePath);
		}else{
			File resourceFile = new File(resourceFilePath);
			String fileName = resourceFile.getName();
			resourceFilePath = resourceFilePath.substring(0,resourceFilePath.length()-fileName.length()-1);
			if(resourceFilePath.endsWith("!")){
				resourceFilePath = resourceFilePath.substring(0,resourceFilePath.length()-1);
			}
			URL fileURL = FileUtil.toURL(resourceFilePath);
			return new File(fileURL.getFile().replaceAll("%20", " "));
		}
	}
}
